package com.yonyou.gmmc.service.pointactivity.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.yonyou.gmmc.common.sms.SmsHttpClient;
import com.yonyou.gmmc.service.pointactivity.dao.CsmsLogMapper;
import com.yonyou.gmmc.service.pointactivity.dao.EmailAcceptMapper;
import com.yonyou.gmmc.service.pointactivity.dao.EmailLogMapper;
import com.yonyou.gmmc.service.pointactivity.dao.EmailSendMapper;
import com.yonyou.gmmc.service.pointactivity.dao.SmsAcceptMapper;
import com.yonyou.gmmc.service.pointactivity.model.TmEmailSend;
import com.yonyou.gmmc.service.pointactivity.model.TmSmsAccept;
import com.yonyou.gmmc.service.pointactivity.model.TmCsmsLog;
import com.yonyou.gmmc.service.pointactivity.model.TmEmailAccept;
import com.yonyou.gmmc.service.pointactivity.model.TmEmailLog;

/**
 * 发送消息的服务
 * 
 * @author 徐庆锋
 *
 */
@Transactional
@Service("SendMessageService")

public class SendMessageService {

	private Logger logger = Logger.getLogger(SendMessageService.class);

	@Autowired
	private EmailSendMapper emailSendMapper;

	@Autowired
	private EmailAcceptMapper emailAcceptMapper;

	@Autowired
	private EmailLogMapper emailLogMapper;

	@Autowired
	private CsmsLogMapper csmsLogMapper;

	@Autowired
	private SmsAcceptMapper smsAcceptMapper;

	@Value("${DCMS-url}")
	private String dcmsUrl;

	@Value("${SMS-pass}")
	private String smsPass;

	@Value("${SMS-key}")
	private String smsKey;

	@Value("${SMS_CDKEY}")
	private String SMS_CDKEY;

	@Value("${SMS_PASS}")
	private String SMS_PASS;

	@Value("${SMS_BASEURL}")
	private String SMS_BASEURL;
	
/*	private String smsPass = "GMMC";

	private String smsKey = "YONYOU";

	private String SMS_CDKEY = "GZDL-DA0D1JBZMR";

	private String SMS_PASS = "659067";

	private String SMS_BASEURL = "http://sdkhttp.gzdlinfo.cn:8088/sdkproxy/sendsms.action";*/

	/**
	 * 查找发件人，可用状态为1
	 * 
	 * @return
	 */
	public TmEmailSend getEmailSendInfo() {

		TmEmailSend tmEmailSend = emailSendMapper.getEmailSendInfo();
		return tmEmailSend;
	}

	/**
	 * 查找邮件接收人，可用状态为1
	 * 
	 * @return
	 */
	public List<TmEmailAccept> getEmailAcceptInfo() {

		List<TmEmailAccept> tmEmailAccept = emailAcceptMapper.getEmailAcceptInfo();

		return tmEmailAccept;
	}

	/**
	 * 保存邮件日志信息
	 * 
	 * @param tmEmailLog
	 * @param acceptEmailList
	 */
	public void saveEmailLogInfo(TmEmailLog tmEmailLog, List<String> acceptEmailList) {
		Map<String, Object> saveEmailLogMap = new HashMap<String, Object>();
		Long emailGroup = emailLogMapper.getEmailLogInfo(tmEmailLog);
		if (emailGroup == null) {
			emailGroup = 1L;
		}

		for (String acceptEmail : acceptEmailList) {

			saveEmailLogMap.put("sendEmail", tmEmailLog.getSendEmail());
			saveEmailLogMap.put("acceptEmail", acceptEmail);
			saveEmailLogMap.put("state", tmEmailLog.getState());
			saveEmailLogMap.put("sendDate", new Date());
			saveEmailLogMap.put("creatDate", new Date());
			saveEmailLogMap.put("createBy", tmEmailLog.getCreateBy());
			saveEmailLogMap.put("emailGroup", emailGroup + 1);
			emailLogMapper.saveEmailLogInfo(saveEmailLogMap);
		}
	}

	/**
	 * 记录发送邮件给接收人的时间
	 * 
	 * @param acceptEmailList
	 */
	public void saveEmailAcceptInfo(List<String> acceptEmailList) {
		Map<String, Object> saveEmailAcceptMap = new HashMap<String, Object>();
		saveEmailAcceptMap.put("state", 0);
		saveEmailAcceptMap.put("sendDate", new Date());
		saveEmailAcceptMap.put("createDate", new Date());
		saveEmailAcceptMap.put("createBy", 1);
		for (String acceptEmail : acceptEmailList) {
			saveEmailAcceptMap.put("acceptEmail", acceptEmail);
			emailAcceptMapper.saveEmailAcceptInfo(saveEmailAcceptMap);
		}
	}

	/**
	 * 上传文件到临时目录并获取流文件
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> uploadFile(HttpServletRequest req) throws Exception {

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		List<MultipartFile> uploadFiles = ((MultipartHttpServletRequest) req).getFiles("imgFile");

		for (int i = 0; i < uploadFiles.size(); ++i) {
			MultipartFile uploadFile = uploadFiles.get(i);
			if (!uploadFile.isEmpty()) {
				// 获取上传文件的原名
				String uploadFileName = uploadFile.getOriginalFilename();
				logger.info("上传文件的原名:" + uploadFileName);
				/*
				 * 获得输入流 此方法也可用 InputStream input = imgFile.getInputStream();
				 */
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("uploadFileName", uploadFileName);
				param.put("buffer", uploadFile.getBytes());
				// param.put("input", input);
				list.add(param);
			}
		}
		return list;
	}

	/**
	 * 获取流文件
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> uploadFile(List<File> listFile) throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		for (int i = 0; i < listFile.size(); ++i) {
			File uploadFile = listFile.get(i);
			// 获取上传文件的原名
			String uploadFileName = uploadFile.getName();
			logger.info("上传文件的原名:" + uploadFileName);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("uploadFileName", uploadFileName);
			param.put("uploadFile", uploadFile);
			list.add(param);
		}
		return list;
	}

	/**
	 * 通过内容和手机号发送短信
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public void sendSms(String phone, String content) throws Exception {
		String phoneTmp1 = "";
		String phoneTmp2 = phone.replaceAll(",", "");
		Integer count1 = 0; // 不是手机号码计数器
		Integer count2 = 0; // 短信发送失败计数器

		// 记录短信日志信息
		TmCsmsLog tmCsmsLog = new TmCsmsLog();
		tmCsmsLog.setState(1);
		tmCsmsLog.setCreateBy(1);
		tmCsmsLog.setSmsContent(content);

		// 查询日志数据库的编组号
		Long smsGroup = csmsLogMapper.getCsmsLogInfo(tmCsmsLog);
		if (smsGroup == null) {
			smsGroup = 0L;
		}
		tmCsmsLog.setSmsGroup(smsGroup + 1);

		if (StringUtils.isBlank(phoneTmp2)) {
			throw new Exception("手机号为空");
		} else {
			if (phone.indexOf(",") != -1) {
				// 包含多个手机号
				String[] phones = phone.split(",");
				// 判断每个手机号码是否有效，有效则发送短信
				for (int i = 0; i < phones.length; i++) {
					phoneTmp1 = phones[i];
					if (checkPhone(phoneTmp1)) { // 是手机号码
						String result = SmsHttpClient.sendSms(phoneTmp1, content, smsPass, smsKey, SMS_CDKEY, SMS_PASS,
								SMS_BASEURL);
						tmCsmsLog.setState(1);
						if (result != "0") {
							count2++;
							tmCsmsLog.setState(0);
						}
						saveCsmsLogInfo(tmCsmsLog, Long.valueOf(phoneTmp1)); // 保存短信日志
					} else {
						count1++; // 不是手机号码的数量
						tmCsmsLog.setState(0);
						saveCsmsLogInfo(tmCsmsLog, Long.valueOf(phoneTmp1)); // 保存短信日志
					}
				}
				if (count1 != 0) {
					throw new Exception("有" + count1 + "个不是手机号码，未发送");
				}
				if (count2 != 0) {
					throw new Exception("有" + count2 + "个手机号发送短信失败");
				}
			}
		}
	}

	/**
	 * 通过内容发送短信
	 * 
	 * @param content
	 * @param tmSmsPhoneList
	 * @throws Exception
	 */
	public void sendSms(String content, List<Long> tmSmsPhoneList) throws Exception {
		Long phoneTmpInt = null;
		String phoneTmpStr = "";
		Integer count1 = 0; // 不是手机号码计数器
		Integer count2 = 0; // 短信发送失败计数器

		// 记录短信日志信息
		TmCsmsLog tmCsmsLog = new TmCsmsLog();
		tmCsmsLog.setState(1);
		tmCsmsLog.setCreateBy(1);
		tmCsmsLog.setSmsContent(content);

		// 查询日志数据库的编组号
		Long smsGroup = csmsLogMapper.getCsmsLogInfo(tmCsmsLog);
		if (smsGroup == null) {
			smsGroup = 0L;
		}
		tmCsmsLog.setSmsGroup(smsGroup + 1);

		// 判断每个手机号码是否有效，有效则发送短信
		for (int i = 0; i < tmSmsPhoneList.size(); i++) {
			phoneTmpInt = tmSmsPhoneList.get(i);
			phoneTmpStr = String.valueOf(phoneTmpInt);
			if (checkPhone(phoneTmpStr)) { // 是手机号码
				String result = SmsHttpClient.sendSms(phoneTmpStr, content, smsPass, smsKey, SMS_CDKEY, SMS_PASS,
						SMS_BASEURL);
				tmCsmsLog.setState(1);
				if (result != "0") {
					count2++; // 发送短信失败的次数
					tmCsmsLog.setState(0);
				}
				saveCsmsLogInfo(tmCsmsLog, phoneTmpInt); // 保存短信日志
			} else {
				count1++; // 不是手机号码的数量
				tmCsmsLog.setState(0);
				saveCsmsLogInfo(tmCsmsLog, phoneTmpInt); // 保存短信日志
			}
		}
		if (tmSmsPhoneList.size() == 0) {
			throw new Exception("手机号码为空");
		}
		if (count1 != 0) {
			throw new Exception("有" + count1 + "个不是手机号码，未发送");
		}
		if (count2 != 0) {
			throw new Exception("有" + count2 + "个手机号发送短信失败");
		}
	}

	/**
	 * 判断是否是手机号
	 *
	 * @param phone
	 * @return
	 */
	public static boolean checkPhone(String phone) {
		Pattern pattern = Pattern.compile("^(13[0-9]|14[0-9]|15[0-9]|17[0-9]18[0-9])\\d{8}$");
		Matcher matcher = pattern.matcher(phone);
		if (matcher.matches()) {
			return true; // 是手机号码
		}
		return false; // 不是手机号码
	}

	/**
	 * 查找短信接收人，可用状态为1
	 * 
	 * @return
	 */
	public List<TmSmsAccept> getSmsAcceptInfo() {

		List<TmSmsAccept> tmSmsAccept = smsAcceptMapper.getSmsAcceptInfo();

		return tmSmsAccept;
	}

	/**
	 * 保存短信日志信息
	 * 
	 * @param tmEmailLog
	 * @param phoneTmpInt
	 */
	public void saveCsmsLogInfo(TmCsmsLog tmCsmsLog, Long phoneTmpInt) {
		Map<String, Object> saveCsmsLogMap = new HashMap<String, Object>();
		saveCsmsLogMap.put("smsPhone", phoneTmpInt);
		saveCsmsLogMap.put("smsContent", tmCsmsLog.getSmsContent());
		saveCsmsLogMap.put("state", tmCsmsLog.getState());
		saveCsmsLogMap.put("sendDate", new Date());
		saveCsmsLogMap.put("creatDate", new Date());
		saveCsmsLogMap.put("createBy", tmCsmsLog.getCreateBy());
		saveCsmsLogMap.put("smsGroup", tmCsmsLog.getSmsGroup());
		csmsLogMapper.saveCsmsLogInfo(saveCsmsLogMap);

	}

}
